package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * 搜附近服务实现类
 */
@Service
public class LocationApiImpl implements LocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 上报地理位置
     * x表示当地的纬度，y表示当地的经度  113.929778,22.582111
     * GeoJsonPoint:没有实现序列化
     *
     * @param latitude  纬度x
     * @param longitude 经度y
     * @param addrStr   地理位置中文信息
     */
    @Override
    public void saveUpdateLocation(Double latitude, Double longitude, String addrStr, Long userId) {
        /*Double latitude2 = latitude;
        Double longitude2 =longitude;
        if (latitude < longitude) {
            latitude2 = longitude;
            longitude2 = latitude;
        }*/
        //1.根据当前用户id查userLocation位置是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        long nowTime = System.currentTimeMillis();
        //2.如果不存在，则保存
        if (userLocation == null) {
            userLocation = new UserLocation();
            userLocation.setId(ObjectId.get());//主键id
            userLocation.setUserId(userId);//当前用户id
            userLocation.setLocation(new GeoJsonPoint(latitude, longitude));//经纬度
            userLocation.setAddress(addrStr);//中文地理位置信息
            userLocation.setCreated(nowTime);
            userLocation.setUpdated(nowTime);
            userLocation.setLastUpdated(nowTime);
            mongoTemplate.save(userLocation);
        }
        //3.如果存在，则更新
        else {
            Update update = new Update();
            update.set("location", new GeoJsonPoint(latitude, longitude));
            update.set("address", addrStr);
            update.set("updated", nowTime);
            update.set("lastUpdated", nowTime);
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }
    }

    /**
     * 搜附近
     * gender：性别 （非必须） 男
     * distance: 传入的值为空 则为2000米
     */
    @Override
    public List<UserLocationVo> searchNearUser(Long userId, Long distance) {
        //a.根据消费者传入用户id 查询当前用户位置
        Query myQuery = new Query();
        myQuery.addCriteria(Criteria.where("userId").is(userId));
        UserLocation myLocation = mongoTemplate.findOne(myQuery, UserLocation.class);
        GeoJsonPoint location = myLocation.getLocation();//当前用户位置
        //b.将m转为km new Circle(我的位置,半径-搜索距离);
        //new Distance(米/1000, km)
        Circle circle = new Circle(location,new Distance(distance/1000, Metrics.KILOMETERS));
        //c.根据当前用户位置、搜索距离  查询附近用户
        Query nearUserQuery = new Query();
        //Criteria.where(""):根据location进行搜索 //withinSphere():2D球面搜索api
        nearUserQuery.addCriteria(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(nearUserQuery, UserLocation.class);
        return UserLocationVo.formatToList(userLocationList);
    }
}
